/***************************************************************************
 *   Copyright (C) 2010 by Oleg Goncharov  *
 *   $EMAIL$                           *                          
 *                                                                         *
 *   This file is part of ChessVision.                                     *
 *                                                                         *
 *   ChessVision is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include <opencv/cv.h>
#include <opencv/highgui.h>

#include "cgradientfigure.h"

namespace Chess {

/*CFigureGradient::CFigureGradient() {
}*/


bool CFigureGradient::DetectFigures(const cv::Mat& img, const CBoardCells& cells, CPosition& position) {
	//CvSize size = cvGetSize(img);
	int h = cells.Get_h(), color;
	cv::Mat cell;
	double pr;
	
	cv::Mat grey, grad;

	cv::cvtColor(img, grey, CV_BGR2GRAY);
	cv::createDerivFilter(CV_8UC1, CV_8UC1, 1, 1, 5)->apply(grey, grad);
	//cv::Canny(grey, grad,50,100);
	
	cv::Mat mask_big(h, h, CV_8UC1, cv::Scalar::all(0));
	cv::Mat mask_small(h, h, CV_8UC1, cv::Scalar::all(0));
	
	cv::circle(mask_small, cv::Point(h/2, h/2), h/4, cv::Scalar(255), -1);
	cv::circle(mask_big, cv::Point(h/2, h/2), h/3, cv::Scalar(255), -1);
	
	for(int i = 0; i < 8; i++)
		for(int j = 0; j < 8; j++) {
			cell = grad(cells.CellRect(i, j));
			pr = cv::mean(cell, mask_big)[0];
			if (pr > grad_therehold) {
				cell = grey(cells.CellRect(i, j));
				color = cvRound(cv::mean(cell, mask_small)[0]);
				if (std::abs(color - white) < std::abs(color - black)) position.Cell(i, j) = Chess::white;
				else position.Cell(i, j) = Chess::black;
			}
			
			cv::circle(grad, cells.Cell(i,j), h/3, cv::Scalar(255), 1);
		}
	
	cvNamedWindow("grad", 0);
	cv::imshow("grad", grad);
	return true;
}

}

